﻿#include "friendbutton.h"
#include <QDebug>
FriendButton::FriendButton(unsigned int t_id, QString t_icon, QString t_uname, QString t_cname, QObject *parent)
    : QObject(parent),id(t_id), icon(t_icon),user_name(t_uname), comment_name(t_cname)
{
    chatwidget = NULL;
    m_networkManager = new QNetworkAccessManager();
    connect(m_networkManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(slotReplyFinished(QNetworkReply *)));
    //创建buttton
    toolButton = new QToolButton();
    if (NULL != toolButton)
    {
        QString text = "";
        qDebug()<<"line14";
        //设置信息
        if ("" != comment_name)
        {
            //有备注,优先备注
            text = QString("%1<%2>").arg(comment_name).arg(user_name);
        }
        else
        {
            //无备注，直接用户名
            text = user_name;
        }
        qDebug()<<"line25";
        toolButton->setText(text);
        toolButton->setIcon(QPixmap(icon)); //设置头像
        qDebug()<<"line30";
        //toolButton->setIconSize(FRIEND_BUTTON_SIZE); //设置按钮尺寸
        qDebug()<<"line31";
        toolButton->setAutoRaise(true);   //当鼠标离开时，按钮恢复为弹起状态
        toolButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮文字显示在图标旁边
    }
    QNetworkRequest request;
    request.setUrl(QUrl(icon));
    m_networkManager->get(request);
}

// 响应结束，进行结果处理-图片显示或错误处理
void FriendButton::slotReplyFinished(QNetworkReply *reply)
{

    // 获取响应状态码，200表示正常
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();
        QPixmap pixmap;
        pixmap.loadFromData(bytes);
        QSize picSize(16,16);
        pixmap.scaled(picSize, Qt::KeepAspectRatio);
        toolButton->setIcon(pixmap);
        //ui->label_icon->setPixmap(pixmap);
    }
    else
    {
        // 错误处理-显示错误信息，或显示上一次缓存的图片或叉图。
    }
}

void FriendButton::createChatWidget(ChatSocket*ct,int uid,QString uname)
{
    if (NULL == chatwidget)
    {
        chatwidget = new ChatWidget(ct,uid,id,uname,user_name,comment_name);
    }
    chatwidget->setWindowFlags(Qt::WindowStaysOnTopHint);   //设置窗口置于顶层
    chatwidget->show();

    qDebug()<<"show";
}

//FriendButton::~FriendButton()
//{
//    //释放内存
//    if (NULL != toolButton)
//    {
//        delete toolButton;
//        toolButton = NULL;
//    }
//    if (NULL != chatwidget)
//    {
//        qDebug()<<"close chatwidget";
//        chatwidget->close();
//        delete chatwidget;
//        chatwidget = NULL;
//    }
//}
